package com.iscreen.utils.dates;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.iscreen.utils.exceptions.IScreenException;
import com.iscreen.utils.exceptions.IScreenExceptionCodes;

public class DateUtils
{
	public final static String DEFAULT_DATE_FORMAT = "yyyyMMdd";
	
	public static String formatDate(Date date)
	{
		return formatDate(date, DEFAULT_DATE_FORMAT);
	}
	
	public static String formatDate(Date date, String pattern)
	{
		return new SimpleDateFormat(pattern).format(date);
	}

	public static Date parseDate(String date) throws IScreenException
	{
		return parseDate(date, DEFAULT_DATE_FORMAT);
	}

	public static Date parseDate(String date, String pattern) throws IScreenException
	{
		try
		{
			return new SimpleDateFormat(pattern).parse(date);
		}
		catch (ParseException e)
		{
			throw new IScreenException(IScreenExceptionCodes.DATE_PARSE_ERROR,e);
		}
	}
	
	private static int getCalendarUnit(DateUnit unit)
	{
		switch (unit)
		{
		case DAY: return Calendar.DATE;
		case MONTH: return Calendar.MONTH;
		case YEAR: return Calendar.YEAR;
		default: return Calendar.DATE;
		}
	}
	
	public static Date add(Date date, DateUnit unit)
	{
		return add(date, unit, 1);
	}
	
	public static Date add(Date date, DateUnit unit, int amount)
	{
		int calendarUnit = getCalendarUnit(unit);
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(calendarUnit, amount);
		return cal.getTime();
	}
	
	
}
